<template>
    <div class="cargo-owner-page">
        <div class="page-title">货主管理</div>

        <!-- 查询区域 -->
        <div class="search-bar card">
            <div class="form-row">
                <label class="form-label">货主姓名:</label>
                <input v-model.trim="query.name" class="input" placeholder="请输入货主姓名" />

                <label class="form-label">手机号:</label>
                <input v-model.trim="query.phone" class="input" placeholder="请输入手机号" />

                <label class="form-label">驾驶证有效日期:</label>
                <input v-model="query.licenseExpireDate" class="input" type="date" />

                <button class="btn primary" @click="handleSearch">查询</button>
                <button class="btn" @click="handleReset">重置</button>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="toolbar">
            <button class="btn primary" @click="handleCreate">新增</button>
            <button class="btn danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">删除</button>
        </div>

        <!-- 表格 -->
        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th class="col-checkbox">
                            <input type="checkbox" :checked="isAllChecked" @change="toggleAll($event)" />
                        </th>
                        <th>货主姓名</th>
                        <th>手机号</th>
                        <th>单位名称</th>
                        <th>联系地址</th>
                        <th>驾驶证有效日期</th>
                        <th>驾驶证照片</th>
                        <th>备注</th>
                        <th>创建时间</th>
                        <th class="col-actions">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="row in tableList" :key="row.id">
                        <td class="col-checkbox">
                            <input type="checkbox" :checked="selectedIds.includes(row.id)"
                                @change="toggleOne(row.id, $event)" />
                        </td>
                        <td>{{ row.name }}</td>
                        <td>{{ row.phone }}</td>
                        <td>{{ row.company || '-' }}</td>
                        <td>{{ row.address || '-' }}</td>
                        <td>{{ row.licenseExpireDate }}</td>
                        <td>
                            <a href="javascript:void(0)" @click="handlePreview(row)">查看</a>
                        </td>
                        <td>{{ row.remark || '-' }}</td>
                        <td>{{ row.createTime }}</td>
                        <td class="col-actions">
                            <a href="javascript:void(0)" @click="handleEdit(row)">编辑</a>
                            <span class="divider">|</span>
                            <a href="javascript:void(0)" class="danger" @click="handleDelete(row)">删除</a>
                            <span class="divider">|</span>
                            <a href="javascript:void(0)" @click="handleView(row)">查看</a>
                        </td>
                    </tr>
                    <tr v-if="tableList.length === 0">
                        <td class="empty" colspan="10">暂无数据</td>
                    </tr>
                </tbody>
            </table>

            <div class="pagination">
                <div class="summary">共{{ totalPages }}页/{{ totalCount }}条数据</div>
                <div class="pager">
                    <button class="pager-btn" :disabled="page === 1" @click="goTo(page - 1)">‹</button>
                    <button v-for="p in pagesToShow" :key="p" class="pager-btn" :class="{ active: page === p }"
                        @click="goTo(p)">{{ p }}</button>
                    <button class="pager-btn" :disabled="page === totalPages || totalPages === 0"
                        @click="goTo(page + 1)">›</button>
                    <span class="goto">
                        跳至
                        <input class="goto-input" type="number" v-model.number="gotoPage" min="1"
                            :max="Math.max(totalPages, 1)" />
                        页
                        <button class="pager-btn" @click="confirmGoto">确定</button>
                    </span>
                </div>
            </div>
        </div>

        <!-- 图片预览弹窗 -->
        <div v-if="showPreview" class="modal-mask">
            <div class="modal">
                <div class="modal-header">
                    <div>驾驶证照片</div>
                    <button class="modal-close" @click="closePreview">×</button>
                </div>
                <div class="modal-body">
                    <img v-if="previewUrl" :src="previewUrl" alt="预览" class="preview-img" />
                    <div v-else class="empty-tip">暂无图片</div>
                </div>
                <div class="modal-footer">
                    <button class="btn primary" @click="closePreview">确定</button>
                </div>
            </div>
        </div>
        <!-- 详情弹窗 -->
        <div v-if="showDetail" class="modal-mask">
            <div class="modal">
                <div class="modal-header">
                    <div>货主详情</div>
                    <button class="modal-close" @click="closeDetail">×</button>
                </div>
                <div class="modal-body">
                    <div v-if="detailLoading" class="empty-tip">加载中...</div>
                    <div v-else-if="!detail" class="empty-tip">暂无数据</div>
                    <div v-else>
                        <div class="detail-grid">
                            <div class="dg-item"><span class="label">货主姓名：</span><span>{{ detail.ownerName ||
                                detail.name }}</span></div>
                            <div class="dg-item"><span class="label">手机号：</span><span>{{ detail.phoneNumber ||
                                detail.phone }}</span></div>
                            <div class="dg-item"><span class="label">单位名称：</span><span>{{ detail.unitName || '-'
                            }}</span></div>
                            <div class="dg-item"><span class="label">联系地址：</span><span>{{ detail.contactAddress ||
                                detail.address || '-' }}</span></div>
                            <div class="dg-item"><span class="label">驾驶证有效日期：</span><span>{{ detail.licenseValidDate ||
                                '-' }}</span></div>
                            <div class="dg-item"><span class="label">备注：</span><span>{{ detail.remarks || '-' }}</span>
                            </div>
                            <div class="dg-item"><span class="label">创建时间：</span><span>{{ detail.createdAt || '-'
                            }}</span></div>
                            <div class="dg-item"><span class="label">创建人：</span><span>{{ detail.createdBy || '-'
                            }}</span></div>
                            <div class="dg-item"><span class="label">最后修改时间：</span><span>{{ detail.lastModifiedAt || '-'
                            }}</span></div>
                            <div class="dg-item"><span class="label">最后修改人：</span><span>{{ detail.lastModifiedBy || '-'
                            }}</span></div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn primary" @click="closeDetail">确定</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { read, write } from '@/assets/Axios/axiosHttple'

type CargoOwner = {
    id: number
    name: string
    phone: string
    company: string
    address: string
    licenseExpireDate: string
    licenseImageUrl?: string
    remark?: string
    createTime: string
}

// 查询条件
const query = reactive({
    name: '',
    phone: '',
    licenseExpireDate: ''
})

// 服务端数据预留（默认空，后续对接接口）
const tableList = ref<CargoOwner[]>([])
const totalCount = ref(0)

// 选择
const selectedIds = ref<number[]>([])
const isAllChecked = computed(() => tableList.value.length > 0 && tableList.value.every(r => selectedIds.value.includes(r.id)))

// 分页
const page = ref(1)
const pageSize = ref(10)
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))
const pagesToShow = computed(() => {
    const total = totalPages.value
    if (total === 0) return [] as number[]
    const max = 7
    const result: number[] = []
    let start = Math.max(1, page.value - 3)
    let end = Math.min(total, start + max - 1)
    if (end - start + 1 < max) start = Math.max(1, end - max + 1)
    for (let i = start; i <= end; i++) result.push(i)
    return result
})
const gotoPage = ref<number | ''>('')
const router = useRouter()




function goTo(p: number) {
    if (p < 1 || p > totalPages.value) return
    page.value = p
    fetchList()
}
function confirmGoto() { if (typeof gotoPage.value === 'number') goTo(gotoPage.value) }

function handleSearch() { page.value = 1; fetchList() }
function handleReset() { query.name = ''; query.phone = ''; query.licenseExpireDate = ''; page.value = 1; fetchList() }

function toggleAll(ev: Event) {
    const checked = (ev.target as HTMLInputElement).checked
    if (checked) selectedIds.value = Array.from(new Set([...selectedIds.value, ...tableList.value.map(r => r.id)]))
    else {
        const ids = new Set(tableList.value.map(r => r.id))
        selectedIds.value = selectedIds.value.filter(id => !ids.has(id))
    }
}
function toggleOne(id: number, ev: Event) {
    const checked = (ev.target as HTMLInputElement).checked
    if (checked) { if (!selectedIds.value.includes(id)) selectedIds.value.push(id) }
    else selectedIds.value = selectedIds.value.filter(x => x !== id)
}

function handleCreate() { router.push('/AddCargoOwner') }
function handleEdit(row: CargoOwner) { router.push({ path: '/UpdateCargoOwner', query: { id: String(row.id) } }) }
async function handleDelete(row: CargoOwner) {
    if (!confirm(`确认删除【${row.name}】吗？`)) return
    try {
        const res = await write.post('baseinfowrite/api/CargoOwner/DeleteCargoOwnerInfo', {
            id: row.id,
            deletedBy: localStorage.getItem('username') || 'system'
        })
        const json = res?.data
        if (res?.status === 200 && (json?.code === 200 || json?.data === true)) {
            tableList.value = tableList.value.filter(x => x.id !== row.id)
            totalCount.value = Math.max(0, totalCount.value - 1)
            selectedIds.value = selectedIds.value.filter(id => id !== row.id)
        } else {
            console.error('删除失败', json)
        }
    } catch (e) {
        console.error('删除接口异常', e)
    }
}
async function handleBatchDelete() {
    if (selectedIds.value.length === 0) return
    if (!confirm(`确认批量删除选中的 ${selectedIds.value.length} 条记录吗？`)) return
    try {
        const payload = {
            ids: selectedIds.value,
            deletedBy: localStorage.getItem('username') || 'system'
        }
        const res = await write.post('baseinfowrite/api/CargoOwner/BatchDeleteCargoOwner', payload)
        const json = res?.data
        if (res?.status === 200 && (json?.code === 200 || json?.data === true)) {
            const set = new Set(selectedIds.value)
            tableList.value = tableList.value.filter(r => !set.has(r.id))
            totalCount.value = Math.max(0, totalCount.value - set.size)
            selectedIds.value = []
        } else {
            console.error('批量删除失败', json)
        }
    } catch (e) {
        console.error('批量删除接口异常', e)
    }
}
// 详情
const showDetail = ref(false)
const detailLoading = ref(false)
const detail = ref<any>(null)
async function openDetail(id: number) {
    showDetail.value = true
    detailLoading.value = true
    detail.value = null
    try {
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 2000 } })
        const j: any = res?.data ?? { data: [] }
        const arr = Array.isArray(j?.data?.data) ? j.data.data : (Array.isArray(j?.data) ? j.data : [])
        const hit = (arr || []).find((x: any) => Number(x?.id) === id)
        if (hit) detail.value = hit
    } finally {
        detailLoading.value = false
    }
}
function handleView(row: CargoOwner) { openDetail(row.id) }
function closeDetail() { showDetail.value = false }
// 图片预览
const showPreview = ref(false)
const previewUrl = ref<string>('')
function handlePreview(row: CargoOwner) {
    previewUrl.value = row.licenseImageUrl || ''
    showPreview.value = true
}
function closePreview() { showPreview.value = false }

async function fetchList() {
    try {
        const params = {
            PageIndex: page.value,
            PageSize: pageSize.value,
            ownerName: query.name || undefined,
            phoneNumber: query.phone || undefined,
            licenseValidDate: query.licenseExpireDate || undefined
        }
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params })
        const json: any = res?.data ?? { data: [] }
        const payload = json?.data ?? { totalCount: 0, data: [] }
        const list = Array.isArray(payload?.data) ? payload.data : []
        tableList.value = (list || []).map((it: any, idx: number) => ({
            id: it.id ?? idx + 1,
            name: it.ownerName ?? it.name ?? it.owner ?? '',
            phone: it.phoneNumber ?? it.phone ?? it.mobile ?? '',
            company: it.unitName ?? it.company ?? it.unit ?? '',
            address: it.contactAddress ?? it.address ?? '',
            licenseExpireDate: it.licenseValidDate ?? it.licenseExpireDate ?? it.licenseExpiryDate ?? '',
            licenseImageUrl: Array.isArray(it.licensePhoto) ? (it.licensePhoto[0] ?? '') : (it.licensePhoto ?? it.licenseImageUrl ?? ''),
            remark: it.remarks ?? it.remark ?? '',
            createTime: it.createdAt ?? it.createTime ?? ''
        }))
        totalCount.value = Number(payload.totalCount ?? tableList.value.length)
    } catch (e) {
        console.error('获取货主列表失败', e)
        tableList.value = []
        totalCount.value = 0
        alert('加载货主列表失败，请检查后端服务')
    }
}

// 首次加载
fetchList()

// 如果从新增页带着 refresh=1 返回，则自动刷新
if (new URLSearchParams(location.search).get('refresh') === '1') {
    handleSearch()
    // 清除一次性参数
    const url = new URL(location.href)
    url.searchParams.delete('refresh')
    history.replaceState(null, '', url.toString())
}
</script>

<style scoped>
.cargo-owner-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.search-bar {
    padding: 16px;
    margin-bottom: 12px;
}

.form-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px 12px;
}

.form-label {
    color: #666;
}

.input {
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
    min-width: 180px;
}

.btn {
    height: 32px;
    padding: 0 14px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn.danger {
    color: #f56c6c;
    border-color: #f56c6c;
}

.toolbar {
    margin: 8px 0 12px 0;
    display: flex;
    gap: 8px;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table thead th {
    text-align: left;
    background: #f7f8fa;
    border-bottom: 1px solid #e5e6eb;
    padding: 10px 12px;
    color: #666;
    font-weight: 400;
}

.table tbody td {
    border-bottom: 1px solid #f0f0f0;
    padding: 10px 12px;
}

.col-checkbox {
    width: 36px;
}

.col-actions {
    width: 168px;
    white-space: nowrap;
}

.divider {
    color: #d0d0d0;
    margin: 0 6px;
}

.danger {
    color: #f56c6c;
}

.empty {
    text-align: center;
    color: #909399;
}

.pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
}

.summary {
    color: #909399;
}

.pager {
    display: flex;
    align-items: center;
    gap: 4px;
}

.pager-btn {
    min-width: 28px;
    height: 28px;
    padding: 0 8px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 3px;
    cursor: pointer;
}

.pager-btn.active {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.goto {
    margin-left: 8px;
    color: #606266;
}

.goto-input {
    width: 56px;
    height: 28px;
    margin: 0 6px;
    padding: 0 6px;
    border: 1px solid #dcdfe6;
    border-radius: 3px;
}

/* 预览弹窗样式 */
.modal-mask {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .35);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
}

.modal {
    width: 640px;
    max-width: 92vw;
    background: #fff;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, .2);
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 14px;
    background: #f7f8fa;
    border-bottom: 1px solid #ebeef5;
}

.modal-close {
    border: none;
    background: transparent;
    font-size: 18px;
    cursor: pointer;
}

.modal-body {
    padding: 12px 14px;
    text-align: center;
}

.preview-img {
    max-width: 100%;
    max-height: 70vh;
    border-radius: 4px;
}

.empty-tip {
    color: #909399;
    padding: 40px 0;
}

.modal-footer {
    padding: 10px 14px;
    text-align: right;
    border-top: 1px solid #ebeef5;
}

.detail-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px 16px;
    text-align: left;
}

.dg-item {
    display: flex;
}

.dg-item .label {
    width: 120px;
    color: #666;
}
</style>
